import logging,os,datetime,traceback, sys
class LOG:
    def __init__(self,logger):

        #param
        self.fileHandlerName = ''
        self.fileHandler = None
        self.loggerName = logger
        self.logger = logging.getLogger(logger)
        self.logger.setLevel(logging.DEBUG)
        self.formatter = logging.Formatter("=============================================\nTime:       %(asctime)s \nFolder:     %(name)s \nLevel:      %(levelname)s"
                                           " \nFile:       %(filename)s \nFunc:       %(funcName)s \nLine No.:   %(lineno)d \nMessage:     %(message)s")

        #console
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        ch.setFormatter(self.formatter)
        self.logger.addHandler(ch)
        path = os.path.abspath(os.path.dirname(__file__)) + '/log/'+self.loggerName+'/'
        print('LogPath:     ', path)


    def setfh(self):
        lfname = datetime.datetime.now().strftime("%Y%m%d-%H:%M:%S:%f")
        if lfname != self.fileHandlerName:
            if self.fileHandler != None:
                self.logger.removeHandler(self.fileHandler)

            #set logs dir
            path = os.path.abspath(os.path.dirname(__file__)) + '/log/'+self.loggerName+'/'
            print(path)
            if os.path.isdir(path) == False:
                os.makedirs(path)

            #set log file
            lf = logging.FileHandler(path+lfname+'.log')
            lf.setLevel(logging.DEBUG)
            lf.setFormatter(self.formatter)
            self.logger.addHandler(lf)
            self.fileHandlerName = lfname
            self.fileHandler = lf

    def _fmtInfo(self, msg):
        if len(msg) == 0:
            msg = traceback.format_exc()
            return msg
        else:
            _tmp = [msg[0]]
            _tmp.append(traceback.format_exc())
            return '\n'.join(_tmp)



    def debug(self, *msg):

        _info = self._fmtInfo(msg)
        try:
            self.setfh()
            self.logger.debug(_info)
        except:
            print('debug log:' + _info)



    def error(self,*msg):

        _info = self._fmtInfo(msg)
        try:
            self.setfh()
            self.logger.error(_info)
        except:
            print('error log:' + _info)



    def info(self,*msg):

        _info = self._fmtInfo(msg)
        try:
            self.setfh()
            self.logger.info(_info)
        except:
            print('info log:' + _info)



    def warning(self,*msg):

        _info = self._fmtInfo(msg)
        try:
            self.setfh()
            self.logger.error(_info)
        except:
            print('warning log:' + _info)